﻿using System.Text;

namespace LowCoding.Common
{
    public class SignHelper
    {
        /// <summary>
        /// 将集合key以ascii码从小到大排序
        /// </summary>
        /// <param name="sArray"></param>
        /// <returns></returns>
        public static IDictionary<string, object> AsciiDictionary(IDictionary<string, object> sArray)
        {
            IDictionary<string, object> asciiDic = new Dictionary<string, object>();
            string[] arrKeys = sArray.Keys.ToArray();
            Array.Sort(arrKeys, string.CompareOrdinal);
            foreach (var key in arrKeys)
            {
                asciiDic.Add(key, sArray[key]);
            }
            return asciiDic;
        }

        public static string GetParamsStr(IDictionary<string, object> sArray, string merchantkey)
        {
            IDictionary<string, object> nowArray = AsciiDictionary(sArray);

            StringBuilder prestr = new StringBuilder();
            foreach (KeyValuePair<string, object> temp in nowArray)
            {
                prestr.Append(temp.Key + "=" + temp.Value.ToString() + "&");
            }
            prestr.Append("KEY=" + merchantkey);
            return MD5Encrypt.GetMD5(prestr.ToString());
        }

        public static string GetParamsSign(IDictionary<string, object> sArray, string merchantkey)
        {
            IDictionary<string, object> nowArray = AsciiDictionary(sArray);

            StringBuilder prestr = new StringBuilder();
            foreach (KeyValuePair<string, object> temp in nowArray)
            {
                prestr.Append(temp.Key + "=" + temp.Value.ToString() + "&");
            }
            prestr.Append("KEY=" + merchantkey);
            return MD5Encrypt.GetMD5(MD5Encrypt.GetMD5(prestr.ToString()));
        }
    }
}